<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="showDialogAction(null)" style="margin: 10px 0">新增
    </el-button>
    <el-table border="border" :data="tableData" style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
      <el-table-column prop="createBy" label="创建人" width="100"></el-table-column>
      <el-table-column prop="updateTime" label="编辑时间" width="150"></el-table-column>
      <el-table-column prop="updateBy" label="编辑人" width="100"></el-table-column>
      <!--      <el-table-column prop="prop" label="操作" width="280">-->
      <!--        <template slot-scope="{row,$index}">-->
      <!--          <el-button icon="el-icon-edit" @click="showDialogAction(row)" type="primary">编辑</el-button>-->
      <!--          <el-button icon="el-icon-s-promotion" @click="showAuthorizationDialogAction(row)" type="warning">授权-->
      <!--          </el-button>-->
      <!--          <el-button icon="el-icon-delete" type="danger" @click="delAction(row.roleId)">删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->


      <el-table-column prop="prop" label="操作" align="center" fixed="right" width="180">
        <template slot-scope="{row,$index}">
          <el-button @click="showDialogAction(row)" type="primary" icon="el-icon-edit" circle></el-button>
          <el-button type="warning" @click="showAuthorizationDialogAction(row)" icon="el-icon-star-off" circle
          ></el-button>
          <el-button @click="delAction(row)" type="danger" icon="el-icon-delete" circle></el-button>
        </template>
      </el-table-column>


    </el-table>

    <!--    current-page 当前页-->
    <el-pagination
      style="margin-top: 20px;text-align: center"
      @current-change="handleCurrentChange"
      :current-page.sync="pageDto.pageNum"
      :page-size="pageDto.pageSize"
      :page-count="7"
      background
      layout="total, prev, pager, next,jumper"
      :total="total"
    >
    </el-pagination>


    <el-dialog style="width: 80%" :title="title+'角色信息'" :before-close="handleClose"
               :visible.sync="dialogFormVisible"
    >
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" placeholder="请输入角色描述" prop="description" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAction('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="addAction">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog style="width: 60%;margin: 0 auto" :title="'给【' +roleName+'】授权菜单'"
               :before-close="handleAuthorizationClose"
               :visible.sync="dialogAuthorizationFormVisible"
    >
      <el-form :model="formAuthorization" ref="ruleFormAuthorization" :rules="rulesAuthorization">
        <el-form-item label="选择菜单" label-width="80px">
          <el-tree
            :data="menusTree"
            show-checkbox
            :default-checked-keys="formAuthorization.menusIds"
            default-expand-all
            node-key="menuId"
             ref="tree"
            highlight-current
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAuthorizationAction()">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="addAuthorizationAction">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import * as api from './api'
import { test } from './api'

export default {
  name: 'index',
  data() {
    return {
      title: '新增',
      roleName: '',
      pageDto: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      tableData: [],
      loading: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',

      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'change' }
        ]
      },
      rulesAuthorization: {},

      form: {
        roleId: null,
        roleName: '',
        description: ''
      },
      formAuthorization: {
        roleId: null,
        menusIds: []
      },
      dialogAuthorizationFormVisible: false,
      menusTree: [],
      pageDto2: {},
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  // 组件加载完毕发出请求
  mounted() {
    this.pageAction()
  },
  methods: {
    resetForm() {
      this.form = {
        roleId: null,
        roleName: '',
        description: ''
      }
    },

    resetAuthorizationForm() {
      this.formAuthorization = {
        roleId: null,
        menusIds: []
      }
    },
    // 加载分页
    async pageAction() {
      // await api.test(this.pageDto)
      const result = await api.pageRequest(this.pageDto)
      this.tableData = result.data.list
      this.total = result.data.total

    },
    // 点击切换页码
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageDto.pageNum = val
      this.pageAction()
    },
    showDialogAction(row) {
      if (row === null) {
        this.dialogFormVisible = true
        this.title = '新增'
        // 浅拷贝、表格不会跟着变
        // this.form = {...row}
      } else {
        // 浅拷贝、表格不会跟着变
        this.dialogFormVisible = true
        this.title = '编辑'
        this.form = { ...row }
      }
    },


    delAction(row) {
      this.$confirm('确认删除？')
        .then(_ => {
          api.delRequest(row.roleId).then(res => {
            if (200 === res.code) {
              //弹出提示
              this.$message({
                message: res.msg,
                type: 'success'
              })
              //刷新页面
              this.pageAction()
            }
          })
        })
        .catch(_ => {
        })



    },




    cancelAction() {

      this.$refs.ruleForm.resetFields()
      this.dialogFormVisible = false
      // this.resetForm()
    },
    //取消新增/编辑弹窗页面
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.$refs.ruleForm.resetFields()
          // this.$refs['ruleForm'].resetFields();
          // this.resetForm()
          done()
        })
        .catch(_ => {
        })
    },

    handleAuthorizationClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          //清空表单验证字
          this.$refs['ruleFormAuthorization'].resetFields()
          //清空form
          this.resetAuthorizationForm()
          //清空tree
          this.resetChecked()
          done()
        })
        .catch(_ => {
        })
    },

    addAction() {
      // <el-form :model="form"  ref="ruleForm"  :rules="rules">
      this.$refs.ruleForm.validate((valid) => {
        this.loading = true
        if (valid) {
          // 请求接口
          api.addRequest(this.form).then(res => {
            if (200 === res.code) {
              this.loading = false
              // 关闭弹窗
              this.dialogFormVisible = false
              // 弹出提示
              this.$message({
                // message: res.msg,
                message: this.form.id === null ? '新增成功' : '编辑成功',
                type: 'success'
              })
              // 刷新页面
              this.pageAction()
              // 清空form表单
              this.resetForm()
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 授权打开菜单框
    showAuthorizationDialogAction(row) {
      api.listWithTree(this.pageDto2).then(res => {
        this.menusTree = res.data
        // 打开授权菜单
        this.dialogAuthorizationFormVisible = true
        // 赋值角色ID
        this.formAuthorization.roleId = row.roleId
        console.log(row.roleId)
        // 回显赋值
        api.detailRequest(row.roleId).then(res => {
          this.formAuthorization.menusIds = res.data.checkedMenus.split(",");
          this.roleName = res.data.roleName
        })
      })
    },
    addAuthorizationAction() {
      console.log(this.$refs.tree.getCheckedKeys())
      console.log(this.$refs.tree.getHalfCheckedKeys())
      // 选择节点
      this.formAuthorization.menusIds = this.$refs.tree.getCheckedKeys()
      // 半选中节点
      const halfCheckedNodes = this.$refs.tree.getHalfCheckedKeys()
      // let newArr = checkedNodes.concat(halfCheckedNodes)
      this.$refs.ruleFormAuthorization.validate((valid) => {
        if (valid) {
          api.addRoleMenus(this.formAuthorization).then(res => {
            if (200 === res.code) {
              // 关闭弹窗
              this.dialogAuthorizationFormVisible = false
              // 弹出提示
              this.$message({
                message: '授权成功',
                type: 'success'
              })
              // 刷新页面
              this.pageAction()
              // 清空form表单
              this.resetAuthorizationForm()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelAuthorizationAction() {
      this.dialogAuthorizationFormVisible = false
      this.resetChecked()
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([])
    }
  }
}
</script>

<style>
element.style {
  height: 120px;
}
</style>
